import type { cartType, detail } from '../../type/home'

type actType = 'addGood' | 'totalNum' | 'delGood' | 'isSelect'
const CartStore = (
  state = [] as detail[],
  action: { type: actType; payload: detail }
) => {
  switch (action.type) {
    //加入购物车
    case 'addGood':
      const oldGoods = state.find(
        item => item.proid === action.payload.proid
      ) as any
      if (oldGoods) {
        oldGoods.number += action.payload.number as number
        state = JSON.parse(JSON.stringify(state))
        return [...state]
      }
      return [...state, action.payload]
    //改变数量
    case 'totalNum':
      const old = state.find(item => item.proid === action.payload.proid)
      if (old) {
        old.number = action.payload.number
        return [...state]
      } else {
        return state
      }
    //删除商品
    case 'delGood':
      state = state.filter(item => item.proid != action.payload.proid)
      return state
    //改变单选
    case 'isSelect':
      const oldselt = state.find(item => item.proid === action.payload.proid)
      if (oldselt) {
        oldselt.state = action.payload.state
        return [...state]
      } else {
        return state
      }
    default:
      return state
  }
}

export default CartStore
